package com.example.config.security;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.utils.StringUtils;
import com.example.config.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Component
//@Order(-1)
public class TokenFilter extends OncePerRequestFilter {
    @Autowired
    @Qualifier("redis1")
    private RedisTemplate redisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            filterChain.doFilter(request,response);
            return;
        }
        Boolean verityToken = JwtUtil.verityToken(token);
        if(!verityToken){
            throw new RuntimeException("token非法");
        }
        Map<String, Object> map = JwtUtil.tokenInfo(token);
        String id =(String) map.get("id");
        Collection<? extends GrantedAuthority> loginUser =
                (Collection<? extends GrantedAuthority>) redisTemplate.opsForValue().get(id);
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("请重新登录");
        }
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(id,null,loginUser);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        filterChain.doFilter(request,response);
    }
}
